package com.baidu.jingyan.view;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.io.FileUtils;

import com.baidu.jingyan.model.Jingyan;
import com.baidu.jingyan.util.DBUtil;
import com.baidu.jingyan.util.DateUtils;
import com.baidu.jingyan.util.HttpUtils;

public class Launch {
	public static final Integer COUNTS = 10;
	DBUtil dbUtil = DBUtil.getInstance();
	public static void main(String[] args) {
		Launch launch = new Launch();
		for (int i = 0; i < COUNTS; i++) {
			launch.randomAndSnatch();
		}
//		launch.randomAndSnatch();
//		Timer timer = new Timer();
//		TimerTask timerTask = new TimerTask() {
//			@Override
//			public void run() {
//				Launch launch = new Launch();
//				for (int i = 0; i < COUNTS; i++) {
//					launch.randomAndSnatch();
//					try {
//						Thread.sleep(new Random().nextInt(60)*1000);
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
//				}
//			}
//		};
//		timer.schedule(timerTask, new Date(), 1000*60*60*24);
//		String html = HttpUtils.doGetForJingyan("http://jingyan.baidu.com/article/da1091fb08f198027849d613.html", "FlashFXP怎么使用", null);
//		System.out.println(html);
		try {
//			String count = FileUtils.readFileToString(new File(System.getProperty("user.dir")+File.separator+"bin"+File.separator+"counts.txt"));
			String count = FileUtils.readFileToString(new File(new URI(Launch.class.getResource("/")+"counts.txt")));
			System.out.println(count);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
	}
	
	public void randomAndSnatch() {
		List<Jingyan> jingyans = dbUtil.getJingyans();
		if (jingyans != null && !jingyans.isEmpty()) {
			Jingyan jingyan = jingyans.get(new Random().nextInt(jingyans.size()));
			if (jingyan != null && jingyan.getTitle() != null && !jingyan.getTitle().equals("")) {
				String html = HttpUtils.doGetForJingyan(jingyan.getUrl(), jingyan.getTitle(), null);
//				System.out.println(jingyan.getTitle()+"=>"+html);
				System.out.println(DateUtils.getDateTime(DateUtils.datePattern, new Date())+" : "+jingyan.getTitle()+" => +1");
				if (html != null) {
					String sql = "update jingyan set view_count=view_count+1 where id ="+jingyan.getId();
					dbUtil.saveBysql(sql);
				}
			}
		}
	}
}
